package com.demo.supplier.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.supplier.common.Pages;
import com.demo.supplier.common.R;
import com.demo.supplier.constant.ApiConstants;
import com.demo.supplier.dto.SupplierDto;
import com.demo.supplier.exception.BusinessException;
import com.demo.supplier.service.SupplierInfoService;
import com.demo.supplier.vo.SupplierVo;
import com.demo.supplier.vo.SupplierDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Map;

/**
 * 供应商管理控制器
 * 
 * @author demo
 */
@Slf4j
@RestController
@RequestMapping("${api.prefix}" + ApiConstants.SUPPLIERS)
@Api(tags = "供应商管理")
public class SupplierController {

    @Autowired
    private SupplierInfoService supplierInfoService;

    @GetMapping
    @ApiOperation("供应商分页查询")
    public R<Pages<SupplierVo>> pageSuppliers(
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") int current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") int size,
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword) {
        
        Page<SupplierVo> page = supplierInfoService.pageSuppliers(current, size, keyword);
        Pages<SupplierVo> pages = Pages.of(page);
        return R.success(pages);
    }

    @GetMapping("/{id}")
    @ApiOperation("获取供应商详情（包含文件信息）")
    public R<SupplierDetailVo> getSupplierById(@ApiParam("供应商ID") @PathVariable Long id) {
        SupplierDetailVo detailVo = supplierInfoService.getSupplierWithFiles(id);
        return R.success(detailVo);
    }

    @PostMapping
    @ApiOperation("创建供应商")
    public R<String> createSupplier(@Valid @RequestBody SupplierDto supplierDto) {
        supplierInfoService.createSupplier(supplierDto);
        return R.success("供应商创建成功");
    }

    @PutMapping("/{id}")
    @ApiOperation("更新供应商")
    public R<String> updateSupplier(
            @ApiParam("供应商ID") @PathVariable Long id,
            @Valid @RequestBody SupplierDto supplierDto) {
        supplierDto.setId(id);
        supplierInfoService.updateSupplier(supplierDto);
        return R.success("供应商更新成功");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除供应商")
    public R<String> deleteSupplier(@ApiParam("供应商ID") @PathVariable Long id) {
        supplierInfoService.deleteSupplier(id);
        return R.success("供应商删除成功");
    }
}